<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Dynamic Cast</title>
  <meta
 content="C++ Tutorial: Dynamic Cast"
 name="description" />
  <meta
 content="C++ Tutorial, Dynamic Cast, Dynamic_cast, RTTI, upcasting, downcasting"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial - Dynamic Cast </span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>
<br />
<br />
<img src="images/dynamic_cast/ImsilOkJungHo3.png" alt="ImsilOkJungHo3"/>
<br />
<br />
<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="rtti">RTTI</div>
<p><strong>RTTI</strong> is short for <strong>Run-time Type Identification</strong>. RTTI is to provide a standard way for a program to determine the type of object during runtime.</p>
<p>In other words, RTTI allows programs that use pointers or references to base classes to retrieve the actual derived types of the objects to which these pointers or references refer.</p>
<p>RTTI is provided through two operators:</p>
<ul>
	<li>The <strong>typeid</strong> operator, which returns the actual type of the object referred to by a pointer (or a reference). </li>
	<li>The <strong>dynamic_cast</strong> operator, which safely converts from a pointer (or reference) to a base type to a pointer (or reference) to a derived type.</li>
</ul>

<br />
<br />
<div class="subtitle" id="dynamic_cast">The dynamic_cast Operator</div>
<p>An attempt to <strong>convert</strong> an object <strong>into</strong> a <strong>more specific</strong> object. </p>

<p>The <strong>dynamic_cast</strong> operator is intended to be the most heavily used RTTI component. It doesn't give us what type of object a pointer points to. Instead, it answers the question of whether we can <strong>safely assign</strong> the address of an object to a pointer of a particular type.</p>
<p>Unlike other casts, a <strong>dynamic_cast</strong> involves a run-time type check. If the object bound to the <strong>pointer</strong> is not an object of the target type, it fails and the value is <strong>0</strong>. If it's a <strong>reference</strong> type when it fails, then an exception of type <strong>bad_cast</strong> is thrown. So, if we want <strong>dynamic_cast</strong> to throw an exception (<strong>bad_cast</strong>) instead of returning <strong>0</strong>, cast to a reference instead of to a pointer. Note also that the dynamic_cast is the only cast that relies on run-time checking.</p> 
<p>"The need for <strong>dynamic_cast</strong> generally arises because you want to perform derived class operation on a derived class object, but you have only a pointer or reference-to-base" said Scott Meyers in his book "Effective C++". </p> 
<p>Let's look at the example code:</p>
<pre>
class Base { };

class Derived : public Base { };

int main() 
{
	Base b;
	Derived d;

	Base *pb = dynamic_cast&lt;Base*&gt;(&d);      	// #1
	Derived *pd = dynamic_cast&lt;Derived*&gt;(&b); 	// #2

	return 0;
}
</pre>
<p>The #1 is ok because dynamic_cast is always successful when we cast a class to one of its base classes </p>
<p>The #2 conversion has a compilation error:</p>
<pre>
 error C2683: 'dynamic_cast' : 'Base' is not a polymorphic type.
</pre>
<p>It's because base-to-derived conversions are not allowed with dynamic_cast unless the base class is <strong>polymorphic</strong>.</p>
<p>So, if we make the Base class polymorphic by adding virtual function as in the code sample below, it will be compiled successfully.</p>
<pre>
class Base {virtual void vf(){}};

class Derived : public Base { };

int main() 
{
	Base b;
	Derived d;

	Base *pb = dynamic_cast&lt;Base*&gt;(&d);		// #1
	Derived *pd = dynamic_cast&lt;Derived*&gt;(&b); 	// #2

	return 0;
}
</pre>
<p>But at runtime, the #2 cast fails and produces <strong>null pointer</strong>.</p>
<p>Let's look at another example.<p>
<pre>
class Base { virtual void vf(){} };

class Derived : public Base { };

int main() 
{
	Base *pBDerived = new Derived;
	Base *pBBase = new Base;
	Derived *pd;

	pd = dynamic_cast&lt;Derived*&gt;(pBDerived);	#1
	pd = dynamic_cast&lt;Derived*&gt;(pBBase);	#2 

	return 0;
}
</pre>
<p>The example has two dynamic casts from pointers of type <strong>Base</strong> to a point of type <strong>Derived</strong>. But only the #1 is successful.</p>
<p>Even though <strong>pBDerived</strong> and <strong>pBBase</strong> are pointers of type <strong>Base*</strong>, <strong>pBDerived</strong> points to an object of type <strong>Derived</strong>, while <strong>pBBase</strong> points to an object of type <strong>Base</strong>. Thus, when their respective type-castings are performed using <strong>dynamic_cast</strong>, <strong>pBDerived</strong>  is pointing to a full object of class <strong>Derived</strong>, whereas <strong>pBBase</strong>  is pointing to an object of class <strong>Base</strong>, which is an incomplete object of class <strong>Derived</strong>.</p>
<p>In general, the expression 
<pre>
dynamic_cast&lt;Type *&gt;(ptr)
</pre>
converts the pointer <strong>ptr</strong> to a pointer of type <strong>Type*</strong> if the pointer-to object (*ptr) is of type <strong>Type</strong> or else derived directly or indirectly from type <strong>Type</strong>. Otherwise, the expression evaluates to <strong>0</strong>, the null pointer.</p>
<br />
<br />


<div class="subtitle" id="upcasting">Upcasting and Downcasting</div>
<p>Converting a derived-class reference or pointer to a base-class reference or pointer is called <strong>upcasting</strong>. It is always allowed for public inheritance without the need for an explicit type cast.</p>
<p>Actually this rule is part of expressing the <strong>is-a</strong> relationship. A <strong>Derived</strong> object is a <strong>Base</strong> object in that it inherits all the data members and member functions of a <strong>Base</strong> object. Thus, anything that we can do to a <strong>Base</strong> object, we can do to a <strong>Derived</strong> class object.</p>
<p>The <strong>downcasting</strong>, the opposite of upcasting, is a process converting a base-class pointer or reference to a derived-class pointer or reference.</p>
<p>It is now allowed without an explicit type cast. A derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class. </p>

<p>Here is a self explanatory example</p>
<pre>
#include &lt;iostream&gt;
using namespace std;

class Employee { 
private:
	int id;
public:
	void show_id(){}
};

class Programmer : public Employee {
public:
	void coding(){}
};

int main() 
{
	Employee employee;
	Programmer programmer;

	// upcast - implicit upcast allowed
	Employee *pEmp = &programmer;

	// downcast - explicit type cast required
	Programmer *pProg = (Programmer *)&employee;


	// Upcasting: safe - progrommer is an Employee 
	// and has his id to do show_id().
	pEmp->show_id();
	pProg->show_id();

	// Downcasting: unsafe - Employee does not have
	// the method, coding().
       // compile error: 'coding' : is not a member of 'Employee'
	// <font color="blue">pEmp->coding();</font> 
	pProg->coding();

	return 0;
}
</pre>
<br />
<br />


<div class="subtitle" id="typeid">The typeid</div>
<p><strong>typeid</strong> operator allows us to determine whether two objects are the same type.</p>
<p>In the previous example for Upcasting and Downcasting, <strong>employee</strong> gets the method <strong>coding()</strong> which is not desirable. So, we need to check if a pointer is pointing to the Programmer object before we use the method, coding().</p>
<p>Here is a new code showing how to use <strong>typeid</strong>:</p>
<pre>
class Employee { 
private:
	int id;
public:
	void show_id(){}
};

class Programmer : public Employee {
public:
	void coding(){}
};

#include &lt;typeinfo&gt;

int main() 
{
	Employee lee;
	Programmer park;

	Employee *pEmpA = &lee;
	Employee *pEmpB = &park;

	// check if two object is the same
	if(typeid(Programmer) == typeid(lee)) {
		Programmer *pProg = (Programmer *)&lee; 
		pProg->coding();
	}
	if(typeid(Programmer) == typeid(park)) {
		Programmer *pProg = (Programmer *)&park; 
		pProg->coding();
	}

	pEmpA->show_id();
	pEmpB->show_id();

	return 0;
}
</pre>
<p>So, only a programmer uses the <strong>coding()</strong> method.</p>
<p>Note that we included &lt;typeinfo&gt; in the example.
The <strong>typeid</strong> operator returns a reference to a <strong>type_info</strong> object, where <strong>type_info</strong> is a class defined in the <strong>typeinfo</strong> header file. </p>
<br />
<br />
<img src="images/dynamic_cast/ImsilOkJungHo4.png" alt="ImsilOkJungHo4"/>
<br />
<br />


<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />




<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
